package sweezy.anim.updater.geom
{
	import flash.display.DisplayObject;
	import flash.geom.Point;
	import sweezy.anim.core.IPhisycalEasingSupportUpdater;
	import sweezy.anim.core.IPropertyAnimation;
	import sweezy.anim.updater.UpdaterProperty;
	import sweezy.anim.util.Path;

	public class PathUpdater implements IPhisycalEasingSupportUpdater
	{

		private var _point:Point;

		public function PathUpdater()
		{
			_point = new Point();
		}

		public function getMaxDuration(element:Object, property:UpdaterProperty, prefix:String, option:Object, target:IPropertyAnimation):Number
		{
			var path:Path = (option === null ? null : (option = option[prefix]) === null ? null : option.path) as Path;

			if (path == null)
			{
				return 0;
			}

			return path.getLength();
		}

		public function initialize(element:Object, property:UpdaterProperty, prefix:String, option:Object, target:IPropertyAnimation):void
		{
			var t:Number = 0;
			if (option !== null)
			{
				option = option[prefix];
				if (option !== null)
				{
					if ("t" in option)
					{
						t = option[t];
						if (isNaN(t))
						{
							t = 0;
						}
						else if (t < 0)
						{
							t = 0;
						}
						else if (t > 1)
						{
							t = 1;
						}
					}
				}
			}

			while (property !== null)
			{
				if (isNaN(property.end))
				{
					property.end = 0;
				}
				if (isNaN(property.start))
				{
					property.name === "t" ? property.start = t :
						property.start = 0;
				}
				if (property.relative)
				{
					property.end += property.start;
				}

				property = property.next;
			}
		}

		public function update(element:Object, property:UpdaterProperty, prefix:String, fraction:Number, option:Object, target:IPropertyAnimation):void
		{
			var obj:DisplayObject = element as DisplayObject;
			var path:Path = (option === null ? null : (option = option[prefix]) === null ? null : option.path) as Path;
			if (path == null || obj === null)
			{
				return;
			}

			var value:Number;

			while (property !== null)
			{
				if (property.name === "t")
				{
					value = property.start + (property.end - property.start) * fraction;
					value = property.round ? ((value * 2 | 0) - (value | 0)) : value;
					if (value < 0)
					{
						value = 0;
					}
					else if (value > 1)
					{
						value = 1;
					}

					path.pointForT(value, _point);
					obj.x = _point.x;
					obj.y = _point.y;
				}

				property = property.next;
			}
		}
	}
}
